package com.newworld.basketballfire.service.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.ServletException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by George on 2018/7/29.
 * BaseException
 */
@ControllerAdvice
public class BaseException {
    private static Logger logger = LoggerFactory.getLogger(BaseException.class);

    @ExceptionHandler({ArithmeticException.class, ServiceException.class, ServletException.class, HttpRequestMethodNotSupportedException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public Map<String, Object> handleBusException(Exception e) {
        logger.error("Bad Params.", e);
        if (e instanceof ServiceException) {
            return handleResponse((ServiceException) e);
        } else if (e instanceof HttpRequestMethodNotSupportedException) {
            return handleResponse(HttpStatus.NOT_FOUND);
        }
        return handleResponse(HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler({Exception.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public Map<String, Object> handleException(Exception e) {
        logger.error("Internal Server Error.", e);
        return handleResponse(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler({NoHandlerFoundException.class})
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ResponseBody
    public Map<String, Object> handleResourceNotFoundException(Exception e) {
        logger.error("Not Found.", e.getMessage());
        return handleResponse(HttpStatus.NOT_FOUND);
    }

    private Map<String, Object> handleResponse(ServiceException e) {
        Map<String, Object> data = new HashMap<>();
        data.put("code", e.getCode());
        data.put("id", e.getId());
        data.put("msg", e.getMessage());
        return data;
    }

    private Map<String, Object> handleResponse(HttpStatus httpStatus) {
        Map<String, Object> data = new HashMap<>();
        data.put("code", httpStatus.value());
        data.put("id", "error_code.internal_server_error");
        data.put("msg", httpStatus.getReasonPhrase());
        return data;
    }

}
